package xx.iverson.listening_manager.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import xx.iverson.listening_manager.entity.SysUser;
import xx.iverson.listening_manager.result.ReturnResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * xx.iverson.interceptor.LoginInterceptor
 * 描述：
 * on 2025/10/16-下午5:38
 *
 * @author weijx
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行OPTIONS请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 检查session中是否有用户信息
        HttpSession session = request.getSession();
        SysUser user = (SysUser) session.getAttribute("user");

        if (user == null) {
            // 未登录，返回JSON错误信息
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(401);

            ReturnResult<Object> result = ReturnResult.error(401, "未登录");
            ObjectMapper mapper = new ObjectMapper();
            response.getWriter().write(mapper.writeValueAsString(result));
            return false;
        }

        return true;
    }
}